package com.example.auth.controller;

import com.example.auth.entity.User;
import com.example.auth.util.UserContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/chat")
public class ChatFileController {

    private static final Logger logger = LoggerFactory.getLogger(ChatFileController.class);

    @Value("${app.upload.dir:uploads}")
    private String uploadDir;

    @Autowired
    private UserContext userContext;

    /**
     * Upload a chat file
     * @param file The file to upload
     * @return Response containing the file URL and other information
     */
    @PostMapping("/upload-file")
    public ResponseEntity<?> uploadChatFile(@RequestParam("file") MultipartFile file) {
        try {
            // Get the current user
            User currentUser = userContext.getCurrentUser();
            if (currentUser == null) {
                logger.error("Failed to upload file: User not logged in");
                return ResponseEntity.badRequest().body(Map.of("error", "User not logged in"));
            }

            // Create chat files directory
            String chatFilesDir = uploadDir + "/chat_files";
            File directory = new File(chatFilesDir);
            if (!directory.exists()) {
                directory.mkdirs();
                logger.info("Created chat files directory: {}", chatFilesDir);
            }

            // Get the original filename
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || originalFilename.isEmpty()) {
                originalFilename = "Unnamed file";
            }

            // Get the file extension
            String fileExtension = "";
            int lastDotIndex = originalFilename.lastIndexOf(".");
            if (lastDotIndex > 0) {
                fileExtension = originalFilename.substring(lastDotIndex);
            }

            // Generate a unique filename
            String uniqueFilename = UUID.randomUUID().toString() + fileExtension;
            Path filePath = Paths.get(chatFilesDir, uniqueFilename);

            // Save the file
            Files.copy(file.getInputStream(), filePath);
            logger.info("File saved: {}", filePath);

            // Create a relative URL path
            String fileUrl = "/uploads/chat_files/" + uniqueFilename;

            // Return file information
            Map<String, Object> response = new HashMap<>();
            response.put("fileUrl", fileUrl);
            response.put("fileName", originalFilename);
            response.put("fileSize", file.getSize());
            response.put("fileType", file.getContentType());

            logger.info("File uploaded successfully - User: {}, File: {}, URL: {}",
                    currentUser.getUsername(), originalFilename, fileUrl);
            return ResponseEntity.ok(response);

        } catch (IOException e) {
            logger.error("Failed to upload file", e);
            return ResponseEntity.badRequest().body(Map.of("error", "Failed to upload file: " + e.getMessage()));
        } catch (Exception e) {
            logger.error("An exception occurred while processing the file upload request", e);
            return ResponseEntity.badRequest().body(Map.of("error", "Failed to upload file: " + e.getMessage()));
        }
    }
}